package dom4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 解析XML工具类
 * Created at 2015/7/23 20:49
 *
 * @author young
 * @version 1.0.0
 */
public class Xml {

	/**
	 * 当前节点名
	 * */
	private String name = null;
	/**
	 * 当前节点值，仅在没有子节点的时候才有值
	 * */
	private String value = null;

	/**
	 * 子节点集合
	 * */
	private List<Xml> children = new ArrayList<Xml>();

	/**
	 * 节点属性集合
	 * */
	private List<Attr> attributes= new ArrayList<Attr>();

	public Xml(){

	}

	public Xml(String rootName){
		this.name = rootName;
	}

	public Xml(String name, String value){
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public List<Attr> getAttrs() {
		return attributes;
	}

	public int getAttrSize(){
		return attributes.size();
	}

	public void setAttrs(List<Attr> attributes) {
		this.attributes = attributes;
	}

	/**
	 * 获取节点某个属性
	 * */
	public Attr getAttr(String name) {
		for (Attr attribute : attributes){
			if(attribute.getName().equals(name)){
				return attribute;
			}
		}
		return null;
	}

	public void setAttr(String name, String value){
		Attr attr = new Attr();
		attr.setName(name);
		attr.setValue(value);
		attributes.add(attr);
	}

	public boolean hasChild() {
		return children.size() > 0;
	}

	public List<Xml> getChildren() {
		return children;
	}

	public void setChildren(List<Xml> children) {
		this.children = children;
	}

	/**
	 * 获取节点下第N个子节点名为name的节点
	 * */
	public Xml getChild(String name, int index){
		int count = 0;
		for(Xml child : children){
			if(child.getName().equals(name)){
				if(count == index){
					return child;
				}else{
					count++;
				}
			}
		}
		return null;
	}

	/**
	 * 获取第一个名为name子节点
	 * */
	public Xml getChild(String name){
		return getChild(name, 0);
	}

	/**
	 * 获取第N个子节点
	 * */
	public Xml getChild(int index){
		return children.get(index);
	}

	public void setChild(Xml xml){
		children.add(xml);
	}

}
